//
//  ShowDrugDetialViewController.m
//  安好
//
//  Created by lianchuang on 14-11-28.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "ShowDrugDetialViewController.h"
#import "DrugReminderDetialCell.h"
//展示页面始终返回到这个列表页面
#import "TakeDrugReminderViewController.h"
#import "EditDrugReminderViewController.h"
#import "RemindDrugManager.h"
//闹钟
#define ShowCellLineColor [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1]
#define IPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)
@interface ShowDrugDetialViewController ()<UITableViewDelegate,UITableViewDataSource,EditDrugReminderViewControllerDelegate>

/**
 *  时间数组
 */
@property(nonatomic,strong)NSMutableArray * timeDataArray;

@property(nonatomic,strong)UITableView * tableView;

@property(nonatomic,strong)NSArray * openClockTimeArray;

@end

@implementation ShowDrugDetialViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self makeNavBar];
    [self loadData];
    [self makeTableView];
    
   
}


#pragma mark - 导航条
-(void)makeNavBar
{
    self.navigationItem.title = @"用药提醒详情";
    // 返回按钮图片
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    // 完成
    UIBarButtonItem *EditBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_编辑.png"] style:UIBarButtonItemStylePlain target:self action:@selector(editButtonClicked)];
    EditBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = EditBtnImg;
}
//返回到列表页面
-(void)backBtnClicked
{
    //返回之前把所有switch闹钟的开启状态取出
    NSMutableArray * openTimeMuArray = [NSMutableArray arrayWithCapacity:0];
    for (NSInteger i = 0; i < self.timeDataArray.count; i++) {
        UISwitch * openSwitch = (UISwitch *)[self.view viewWithTag:1000+i];
        if (openSwitch.isOn == YES) {
            [openTimeMuArray addObject:self.timeDataArray[i]];
        }
    }
    self.openClockTimeArray = openTimeMuArray;
   
    //把开启的时间存入本地
    NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
    //key是 uid-fid-reminderid
    //如果开启的时间提醒为空就把本地保存一个flag “Empty”
    if (self.openClockTimeArray.count == 0) {
        [timeUser setObject:@[@"Empty"] forKey:[NSString stringWithFormat:@"%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"]]];
    }else{
        
        [timeUser setObject:self.openClockTimeArray forKey:[NSString stringWithFormat:@"%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"]]];
    }
    [timeUser synchronize];
    
    
    TakeDrugReminderViewController * take = [[TakeDrugReminderViewController alloc] init];
    NSInteger k = 0;
    for (NSInteger i = 0; i < self.navigationController.viewControllers.count; i++) {
        if ([self.navigationController.viewControllers[i] isKindOfClass:take.class])
        {
            k = i;
        }
    }
    [self.navigationController popToViewController:self.navigationController.viewControllers[k] animated:YES];

}
//push到编辑页面--并且传值
-(void)editButtonClicked
{
    //在去编辑页面的时候也要把开启的时间数组保存本地
    NSMutableArray * openTimeMuArray = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray * closeTimeArray = [NSMutableArray arrayWithCapacity:0];
    //返回之前  把闹钟所有的开启获取存入本地
    for (NSInteger i = 0; i < self.timeDataArray.count; i++) {
        UISwitch * openSwitch = (UISwitch *)[self.view viewWithTag:1000+i];
        if (openSwitch.isOn == YES) {
            [openTimeMuArray addObject:self.timeDataArray[i]];
        }else
        {
            [closeTimeArray addObject:self.timeDataArray[i]];
        }
    }
    self.openClockTimeArray = openTimeMuArray;
    //把开启的时间存入本地
    NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
    if (self.openClockTimeArray.count == 0) {
        [timeUser setObject:@[@"Empty"] forKey:[NSString stringWithFormat:@"%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"]]];
    }else{
        
    [timeUser setObject:self.openClockTimeArray forKey:[NSString stringWithFormat:@"%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"]]];
    }
    
    //把关闭的时间存入数组
    [timeUser setObject:closeTimeArray forKey:[NSString stringWithFormat:@"关闭%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"]]];
    MyNSLog("关闭闹钟的时间数组 %@", closeTimeArray);
    [timeUser synchronize];
    
    

    EditDrugReminderViewController * editReminder = [[EditDrugReminderViewController alloc] init];
    editReminder.openTimeReminderArray = openTimeMuArray;
    editReminder.closeTimeReminderArray = closeTimeArray;
    editReminder.delegate = self;
    
    editReminder.drugName = self.drugName;
    editReminder.doseCountString = self.doseCountString;
    editReminder.timeString = self.timeString;
    editReminder.familyInfoDic = self.familyInfoDic;

    [self.navigationController pushViewController:editReminder animated:NO];
   
}

#pragma mark - 数据处理
-(void)loadData
{
    self.timeDataArray = [NSMutableArray arrayWithCapacity:0];
    NSArray *timeSubArray = [self.timeString componentsSeparatedByString:@","];
    for (NSString * time in timeSubArray) {
        [self.timeDataArray addObject:time];
    }
    
    //从本地获取--开启闹钟的时间数组
    NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
    NSString * timeKey = [NSString stringWithFormat:@"%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"]];
    
    //如果是nil就是可能换了手机了--那么不管他原来那个手机的闹钟是否开启都将现在这个手机上的时间开启
    if ([timeUser objectForKey:timeKey] == nil) {
        self.openClockTimeArray = self.timeDataArray;
    }else{
        //如果不为空，那么如果的到的是@"Empty"则是原来的时间全是关闭的
        if ([[[timeUser objectForKey:timeKey] firstObject] isEqualToString:@"Empty"]) {
            self.openClockTimeArray = @[];
            
        }else{
            //这就是存入本地的开启switch时间数组
            self.openClockTimeArray = [timeUser objectForKey:timeKey];
        }
    
    }
    
 
}

#pragma mark - tableView--的创建
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    //设置cell之间分割线为None
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

}
#pragma mark - tableView的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (IPhone6Plus) {
        return 12;
    }else{
        return 10.0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (IPhone6Plus) {
        return 53;
    }else{
        return 44;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 2;
    }
    else if(section == 1)
    {
        return self.timeDataArray.count;
    }
    else
    {
        return 0;
    }
}
#pragma mark - ----tableViewCell加载
-(UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DrugReminderDetialCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (cell == nil) {
        if (IPhone6Plus) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DrugReminderDetialCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DrugReminderDetialCell" owner:self options:nil] firstObject];
        }
    }
    //cell上的线
    cell.topLineView.backgroundColor = ShowCellLineColor;
    cell.bottomLineView.backgroundColor = ShowCellLineColor;
    cell.topLineView.height = 0.3;
    cell.topLineView.width = kScreenWidth;
    cell.timeReminderSwitch.right = kScreenWidth-15;
    if (IPhone6Plus) {
        cell.timeReminderSwitch.right = kScreenWidth-20;
    }
    
    if (indexPath.section == 0) {
        cell.timeReminderSwitch.hidden = YES;
        if (indexPath.row == 0) {
            cell.itemLable.text = self.drugName;
            [cell.itemImgView setImage:[UIImage imageNamed:@"药品.png"]];
            cell.bottomLineView.frame = CGRectMake(55,cell.contentView.height-0.5, kScreenWidth-55, 0.5);
            if (IPhone6Plus) {
                cell.bottomLineView.left = 65;
            }
        }
        if (indexPath.row == 1) {
            cell.topLineView.hidden = YES;
            cell.bottomLineView.frame = CGRectMake(0,cell.contentView.height-0.5, kScreenWidth, 0.5);
            cell.itemLable.text = self.doseCountString;
            [cell.itemImgView setImage:[UIImage imageNamed:@"单位.png"]];
        }
        
    }
    if (indexPath.section == 1)
    {
        if (indexPath.row != 0) {
            cell.itemImgView.hidden = YES;
            cell.topLineView.hidden = YES;
            cell.bottomLineView.frame = CGRectMake(0, cell.contentView.height-0.5, kScreenWidth, 0.5);
        }
        if (indexPath.row != self.timeDataArray.count-1) {
            cell.bottomLineView.frame = CGRectMake(55,cell.contentView.height-0.5, kScreenWidth-55, 0.5);
            if (IPhone6Plus) {
                cell.bottomLineView.left = 65;
            }
        }
        //只是第0行的时候显示，在不是0行的时候他被隐藏了
        [cell.itemImgView setImage:[UIImage imageNamed:@"时间.png"]];
        cell.itemDetialLable.hidden = YES;
        cell.itemLable.text = self.timeDataArray[indexPath.row];

        MyNSLog("%@",self.timeDataArray[indexPath.row]);
        
    
        
        //默认先都关闭
        cell.timeReminderSwitch.on = NO;
        //对时间开启数组比对--是否开启
        for (NSString * openTime in self.openClockTimeArray)
        {
            if ([openTime isEqualToString:self.timeDataArray[indexPath.row]]) {
                //该行cell的time在开启的时间数组中则开启
                cell.timeReminderSwitch.on = YES;
                
            }
        }
        cell.timeReminderSwitch.tag = indexPath.row + 1000;
        [cell.timeReminderSwitch addTarget:self action:@selector(timeReminderSwitchValueChanged:) forControlEvents:UIControlEventValueChanged];
        if (self.timeDataArray.count == 1) {
            cell.bottomLineView.frame = CGRectMake(0, cell.contentView.height-0.5, kScreenWidth, 0.5);
        }
        if (IPhone6Plus) {
            cell.timeReminderSwitch.right = kScreenWidth - 20;
        }
        
        
    }

    return cell;

}
#pragma mark - - - switch时间开关触发事件
-(void)timeReminderSwitchValueChanged:(UISwitch *)sender
{
    UISwitch * mySwitch = (UISwitch *)sender;

#pragma mark 本地推送闹钟提醒的 key = @"uid,fid,reminderID,time"
    
    NSString * clockTimeKey = [NSString stringWithFormat:@"%@,%@,%@,%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"],self.timeDataArray[mySwitch.tag-1000]];
    
    //开关开启设置闹钟通知
    if (mySwitch.on == YES) {
        
        [[RemindDrugManager shareInstance] addNewRemindWithUserName:@"" andMedicineName:@"" andMedicineDosage:@"" andNewTime:self.timeDataArray[mySwitch.tag-1000] andMessage:@"" andUserID:@"2" andRemindID:clockTimeKey andFamilyInfoDic:self.familyInfoDic];
    }else
    {
        //关闭--移除闹钟通知---有问题RemindID是NSNumber
        [[RemindDrugManager shareInstance] removeRemindWithRemindID:clockTimeKey];
    }
    
}
#pragma mark - 编辑页面的代理方法--返回来后重新刷新数据
//编辑页面“完成”后返回到展示页面属性页面
-(void)editReminderFinishReloadShowDetialWithDrugName:(NSString *)drugName AndDoseCount:(NSString *)doseCountString AndTimeString:(NSString *)timeString andOpenTimeArray:(NSArray *)openTimeArray
{
    self.drugName = drugName;
    self.doseCountString = doseCountString;
    self.timeString = timeString;
    NSArray * timeArray = [self.timeString componentsSeparatedByString:@","];
    [self.timeDataArray removeAllObjects];
    for (NSString * time in timeArray) {
        [self.timeDataArray addObject:time];
    }
    
    //把开启的闹钟时间取出来
    NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
    //关闭的时间key
    NSString * openTimeKey = [NSString stringWithFormat:@"%@%@%@",self.familyInfoDic[@"uid"],self.familyInfoDic[@"fid"],self.familyInfoDic[@"reminderID"]];
    
    if (openTimeArray == nil) {
        [timeUser setObject:@[@"Empty"] forKey:openTimeKey];
    }else{
        [timeUser setObject:openTimeArray forKey:openTimeKey];
    }
    [timeUser synchronize];
    
    self.openClockTimeArray = openTimeArray;

    [self.tableView reloadData];
}

@end
